<?php

namespace app\index\controller;

use app\admin\model\LinksMessage;
use app\admin\model\LinksMessageViewLog;
use app\admin\model\PostPath;
use app\index\model\PostComment;
use app\index\model\UsersModel;
use think\facade\Log;
use app\index\model\Post as PostModel;

/**
 * 消息中心
 * Class MessageCenter
 * @package app\index\controller
 */
class MessageCenter extends Base
{
    /**
     * 评价回复
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function commentReply()
    {
        $userInfo = $this->checkLogin();
        Log::write('用户:' . $userInfo['nickname'] . '查看了评价回复', 'error');

        if (!$this->request->isPost()) {
            $this->responseJson(10500, '发生异常');
        }

        $param = $this->request->param();
        if (!isset($param['uid'])) {
            $this->responseJson(10500, '参数错误');
        }

        if ($param['uid'] != $userInfo['id']) {
            $this->responseJson(10500, '不允许的操作');
        }

        $idArr = PostModel::where(['uid' => $param['uid']])->column('id');

        // 评论了我的帖子
        $comment = PostComment::whereIn('post_id', $idArr)->where('parent_id', 0)->whereRaw('uid != "' . $param['uid'] . '"')->hidden(['reply_time', 'update_time'])->select();

        $comment = $comment ? $comment->toArray() : [];
//        var_dump($comment);

        foreach ($comment as $k => $v) {
            $comment[$k]['is_reply'] = 0;
        }

        // 查询回复我的评论：根据当前登录的openid查询出我评论的数据对应的id，在根据该id去匹配reply_id所在的数据
        $idArr1 = PostComment::where(['uid' => $param['uid']])->column('id');
//        var_dump($idArr);
        if ($idArr1) {
            $reply = PostComment::whereIn('reply_id', $idArr1)->hidden(['reply_time', 'update_time'])->select();
            $reply = $reply ? $reply->toArray() : [];
            if ($reply) {
                foreach ($reply as $k1 => $v1) {
                    $reply[$k1]['is_reply'] = 1;
                }
            }
        }

        if (isset($reply)) {
            $comment = array_merge($comment, $reply);
        }

        if (empty($comment)) {
            $this->responseJson(10400, 'empty', ['data' => [], 'count' => 0]);
        }

//        var_dump($comment);

        // 组装数据
        foreach ($comment as $k2 => $v2) {
            // 查询当前帖子的状态
            $status = PostModel::where('id', $v2['post_id'])->value('status');
            $comment[$k2]['is_delete'] = 0;
            // 标识是否删除
            if ($status == -1) {
                $comment[$k2]['is_delete'] = 1;
            }
            $users = UsersModel::where('id', $v2['uid'])->field('openid,nickname,headimg')->find();
            $comment[$k2]['nickname'] = emojiDecode($users['nickname']);
            $comment[$k2]['headimg'] = $users['headimg'];
            $comment[$k2]['create_time'] = date('y-m-d H:i', strtotime($v2['create_time']));
            $path = PostPath::where(['post_id' => $v2['post_id'], 'type' => 1])->value('path');
            $comment[$k2]['path'] = $path ? config('url.url') . $path : '';
            // 评价默认为空
            $comment[$k2]['question'] = '';
            // 回复
            if ($v2['is_reply'] == 1) {
                // 获取提问
                $comment[$k2]['question'] = PostComment::where(['id' => $v2['reply_id']])->value('content');

            }
        }

        $page = intval($this->request->param('page')) ?: 1;
        $pageSize = intval($this->request->param('pagesize')) ?: 10;

        // 总条数
        $count = count($comment);
        if ($count) {
            // 按照某个字段对二维数组排序
            array_multisort(array_column($comment, 'create_time'), SORT_DESC, $comment);
        }
        // 根据每页显示的条数作为参数将原数组分割成新的数组
        $newArr = array_chunk($comment, $pageSize);
        // 是否大于总页数
        if ($page - 1 > max(array_keys($newArr))) {
            $data = [];
        } else {
            $data = $newArr[$page - 1];
            if (!$data) {
                $this->responseJson(10400, 'empty');
            }
        }

        $this->responseJson(10200, 'success', ['data' => $data, 'count' => $count]);

    }

    /**
     * 云links通知
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function linksMessage()
    {
        $userInfo = $this->checkLogin();
        Log::write('用户:' . $userInfo['nickname'] . '查看了云links通知', 'error');

        $page = intval($this->request->param('page')) ?: 1;
        $pageSize = intval($this->request->param('pagesize')) ?: 10;

        $whereRaw = "FIND_IN_SET(".$userInfo['id'].",uids) OR uids = 0";
        $data = LinksMessage::where('status', 1)
            ->whereRaw($whereRaw)
            ->order('create_time','desc')
            ->page($page, $pageSize)
            ->hidden(['uids','update_time'])
            ->select();
        $data = $data ? $data->toArray() : [];

        if (empty($data)) {
            $this->responseJson(10400, 'empty', ['data' => [], 'count' => 0]);
        }

        foreach ($data as $k=>$v) {
            $data[$k]['create_time'] = date('y-m-d H:i', strtotime($v['create_time']));
            // 标识当前用户是否已查看该消息
            $isView = LinksMessageViewLog::where(['uid'=>$userInfo['id'],'lmid'=>$v['id']])->find();
            $data[$k]['is_view'] = 0;
            if (!empty($isView)) {
                $data[$k]['is_view'] = 1;
            }
        }

        $count = LinksMessage::where('status', 1)->whereRaw($whereRaw)->count();

        $this->responseJson(10200, 'success', ['data' => $data, 'count' => $count]);
    }

    /**
     * 消息查看状态修改
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function messageView()
    {
        $userInfo = $this->checkLogin();
        Log::write('用户:' . $userInfo['nickname'] . '设置消息已查看', 'error');

        if (!$this->request->isPost()) {
            $this->responseJson(10500, '发生异常');
        }

        $param = $this->request->param();
        // 查看选项  1云links通知  2评论回复
        if (!isset($param['view_type']) || !isset($param['ids']) || empty($param['ids'])) {
            $this->responseJson(10500, '参数错误');
        }

        if ($param['uid'] != $userInfo['id']) {
            $this->responseJson(10500, '不允许的操作');
        }

        $param['ids'] = rtrim($param['ids'], ',');

        if ($param['view_type'] == 1) {
            $view_type = '云links通知';
            $idArr = explode(',',$param['ids']);
            $where = ['uid'=>$param['uid']];
            foreach ($idArr as $ids) {
                $where['lmid'] = $ids;
                $finds = LinksMessage::where($where)->find();
                if (empty($finds)) {
                    $res = LinksMessage::create($where);
                    if (!$res) {
                        $this->responseJson(10500, 'error');
                    }
                }
            }
        } else {
            $view_type = '评论回复';
            // 是否已查看 0否  1是
            $res = PostComment::whereIn('id', $param['ids'])->update(['is_view' => 1]);
            if (!$res) {
                $this->responseJson(10500, 'error');
            }
        }

        Log::write('消息查看状态修改了' . $view_type . 'ID为' . json_encode($param['ids']), 'error');

        $this->responseJson(10200, 'success');

    }

}